package com.x.erp.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * 签名
 */
public class SignatureUtils {
    private static Logger logger = LoggerFactory.getLogger(SignatureUtils.class);
    //加密算法RSA
    public static final String KEY_ALGORITHM = "RSA";
    //签名算法
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
    //签名算法
    public static final String CHARSET = "UTF-8";

    /**
     * 获取私钥对象
     * @param keyString 私钥字符串
     * @return PrivateKey
     */
    private static PrivateKey getPrivateKeyOfZhiTong(String keyString) {
        try {
            byte[] keyBytes = new BASE64Decoder().decodeBuffer(keyString);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            return keyFactory.generatePrivate(keySpec);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 签名
     * @param content 待签名字符串
     * @param privateKeyString 私钥字符串
     * @return 签名字符串
     */
    public static String signOfZhiTong(String content, String privateKeyString) {
        try {
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initSign(getPrivateKeyOfZhiTong(privateKeyString));
            signature.update(content.getBytes(CHARSET));
            return new BASE64Encoder().encodeBuffer(signature.sign());
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

}
